package com.help10000.rms.ui.fragments

import android.content.Intent
import android.graphics.Color
import android.graphics.Typeface
import android.os.Bundle
import android.view.View
import androidx.core.content.ContextCompat
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.amir.common.api.ApiContents
import com.amir.common.beans.ReportR001Data
import com.amir.common.beans.WorkOrderReportEntity
import com.amir.common.weight.DuplicateClickProxy
import com.github.mikephil.charting.animation.Easing
import com.github.mikephil.charting.components.AxisBase
import com.github.mikephil.charting.components.XAxis
import com.github.mikephil.charting.components.YAxis
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.data.LineData
import com.github.mikephil.charting.data.LineDataSet
import com.github.mikephil.charting.formatter.ValueFormatter
import com.help10000.rms.R
import com.help10000.rms.config.globalData
import com.help10000.rms.mvp.presenter.ManagerPresenter
import com.help10000.rms.mvp.view.ManagerView
import com.help10000.rms.ui.activitys.MyWebViewActivity
import com.help10000.rms.ui.activitys.OrderActivity
import com.help10000.rms.ui.base.BaseFragment
import kotlinx.android.synthetic.main.fragment_manager.lineChart
import kotlinx.android.synthetic.main.fragment_manager.ll_auditing
import kotlinx.android.synthetic.main.fragment_manager.ll_create_workorder
import kotlinx.android.synthetic.main.fragment_manager.ll_in_service
import kotlinx.android.synthetic.main.fragment_manager.ll_integrated_query
import kotlinx.android.synthetic.main.fragment_manager.ll_opensea_workorder
import kotlinx.android.synthetic.main.fragment_manager.ll_padding_task
import kotlinx.android.synthetic.main.fragment_manager.ll_tobe_refunded
import kotlinx.android.synthetic.main.fragment_work_order.swiperefresh
import java.text.DecimalFormat
import java.text.SimpleDateFormat

class ManagerFragment : BaseFragment<ManagerPresenter, ManagerView>(),
    View.OnClickListener, ManagerView, SwipeRefreshLayout.OnRefreshListener {
    lateinit var serverDateFormat: SimpleDateFormat
    lateinit var chartLabelDateFormat: SimpleDateFormat

    private var mColor: String?= null

    companion object {
        private const val ARG_COLOR = "color"
        @JvmStatic
        fun newInstance(statusBarColor: String) =
            ManagerFragment().apply {
                arguments = Bundle().apply {
                    putString(ARG_COLOR, statusBarColor)
                }
            }
    }

    override fun getlayoutId(): Int {
        return R.layout.fragment_manager
    }

    override fun initView(rootView: View?) {
        arguments?.let {
            mColor = it.getString(ARG_COLOR)
        }
        //上面的方法已经废弃
        swiperefresh.setColorSchemeColors(
            resources.getColor(R.color.colorPrimary),
            resources.getColor(R.color.colorPrimary),
            resources.getColor(R.color.colorPrimary),
            resources.getColor(R.color.colorPrimary)
        )

        serverDateFormat = SimpleDateFormat("yyyy-MM-dd")
        chartLabelDateFormat = SimpleDateFormat("MM.dd")
        lineChart.setNoDataText("没有最近的工单数据")
    }

    fun loadLineChart(dataList:List<ReportR001Data>){
        lineChart.setBackgroundColor(Color.WHITE)
        lineChart.description.isEnabled = false
        lineChart.setDrawGridBackground(false)
        lineChart.animateY(3000, Easing.EaseOutBack);
        var xAxis = lineChart.xAxis
        xAxis.position = XAxis.XAxisPosition.BOTTOM
        xAxis.setDrawGridLines(false)

        val formatter: ValueFormatter = object : ValueFormatter() {
            override fun getAxisLabel(value: Float, axis: AxisBase): String {
                // 处理chart拉动后，XAxis显示坐标不对应数组情况
                if (value.toInt()< 0 || value.toInt() >= dataList.size) return ""
                val dateStr = dataList.elementAt(value.toInt()).CountDate
                val date = serverDateFormat.parse(dateStr)
                return chartLabelDateFormat.format(date)
            }
        }

        xAxis.granularity = 1f
        xAxis.valueFormatter = formatter

        val yRightAxis: YAxis = lineChart.axisRight
        yRightAxis.isEnabled = false

        val yLeftAxis: YAxis = lineChart.axisLeft
        yLeftAxis.typeface = Typeface.MONOSPACE
        yLeftAxis.granularity = 5f
        yLeftAxis.spaceBottom = 5F
        yLeftAxis.gridColor = ContextCompat.getColor(this.requireContext(), R.color.chart_grid_line);
        yLeftAxis.setDrawZeroLine(true)
        yLeftAxis.zeroLineWidth = 2f
        yLeftAxis.zeroLineColor = Color.WHITE
        yLeftAxis.spaceTop = 20f
//        yLeftAxis.isGranularityEnabled = true


        var entries = ArrayList<Entry>()
        dataList.forEachIndexed { index, element ->
            entries.add(Entry(index.toFloat(), element.TotalQty.toFloat()))
        }

        var dataSet = LineDataSet(entries, null)
        dataSet.color = ContextCompat.getColor(this.requireContext(), R.color.chart_line);
        dataSet.lineWidth = 2f;
//        dataSet.setDrawFilled(true);
//        dataSet.fillDrawable = ContextCompat.getDrawable(this.requireContext(), R.drawable.line_gradient_bg_shape)
        dataSet.fillAlpha = 0;
//        dataSet.setDrawCircleHole(false);
        dataSet.circleRadius = 0f;
        dataSet.setDrawValues(false);
        dataSet.mode = LineDataSet.Mode.CUBIC_BEZIER
        dataSet.setDrawCircles(false);
        dataSet.highLightColor = ContextCompat.getColor(this.requireContext(), R.color.chart_highlight_line);
        dataSet.valueTextColor = ContextCompat.getColor(this.requireContext(), R.color.chart_line);
        dataSet.valueTextSize = 14f;
        dataSet.valueFormatter = object : ValueFormatter() {
            val format = DecimalFormat("##")
            override fun getFormattedValue(v: Float): String {
                return format.format(v)
            }
        }

        val lineData = LineData(dataSet)
        lineChart.data = lineData
        lineChart.invalidate()
    }

    override fun initData(savedInstanceState: Bundle?) {

    }

    override fun initListener() {
        swiperefresh.setOnRefreshListener(this)
        ll_create_workorder.setOnClickListener(DuplicateClickProxy(this))
        ll_opensea_workorder.setOnClickListener(DuplicateClickProxy(this))
        ll_tobe_refunded.setOnClickListener(DuplicateClickProxy(this))
        ll_padding_task.setOnClickListener(DuplicateClickProxy(this))
        ll_in_service.setOnClickListener(DuplicateClickProxy(this))
        ll_auditing.setOnClickListener(DuplicateClickProxy(this))
        ll_integrated_query.setOnClickListener(DuplicateClickProxy(this))
    }

    override fun onResume() {
        super.onResume()
        mPresenter.getData()
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.ll_order -> {//我的订单
                startActivity(Intent(mContext, OrderActivity::class.java))
            }
            R.id.ll_create_workorder -> {//录单
                val intent = Intent(mContext, MyWebViewActivity::class.java)
                val url = "${ApiContents.webBaseUrl}${globalData.CmpyCatg?.PreUrlForEmp}OrderAdd.aspx?AccessToken=${globalData.token?.access_token}"
//                val url = "http://192.168.3.56:3000"
                intent.putExtra("url",
                    url)
                intent.putExtra("title", "")
                intent.putExtra("hideNav", true)
                intent.putExtra("color", mColor)
                startActivity(intent)
            }
            R.id.ll_opensea_workorder -> {//公海工单
                val intent = Intent(mContext, MyWebViewActivity::class.java)
                val url = "${ApiContents.webBaseUrl}${globalData.CmpyCatg?.PreUrlForEmp}PublicList.aspx?AccessToken=${globalData.token?.access_token}"
                intent.putExtra("url",
                    url)
                intent.putExtra("title", "")
                intent.putExtra("hideNav", true)
                intent.putExtra("color", mColor)
                startActivity(intent)
            }
            R.id.ll_tobe_refunded -> {//待退款
                val intent = Intent(mContext, MyWebViewActivity::class.java)
                val url = "${ApiContents.webBaseUrl}${globalData.CmpyCatg?.PreUrlForEmp}ArbitrateList.aspx?AccessToken=${globalData.token?.access_token}"
                intent.putExtra("url",
                    url)
                intent.putExtra("title", "")
                intent.putExtra("hideNav", true)
                intent.putExtra("color", mColor)
                startActivity(intent)
            }
            R.id.ll_padding_task -> { //待安排
                val intent = Intent(mContext, MyWebViewActivity::class.java)
                val url = "${ApiContents.webBaseUrl}${globalData.CmpyCatg?.PreUrlForEmp}AssList_2.aspx?AccessToken=${globalData.token?.access_token}"
                intent.putExtra("url",
                    url)
                intent.putExtra("title", "")
                intent.putExtra("hideNav", true)
                intent.putExtra("color", mColor)
                startActivity(intent)
            }
            R.id.ll_in_service -> {//服务中
                val intent = Intent(mContext, MyWebViewActivity::class.java)
                val url = "${ApiContents.webBaseUrl}${globalData.CmpyCatg?.PreUrlForEmp}AssList.aspx?AccessToken=${globalData.token?.access_token}"
                intent.putExtra("url",
                    url)
                intent.putExtra("title", "")
                intent.putExtra("hideNav", true)
                intent.putExtra("color", mColor)
                startActivity(intent)
            }
            R.id.ll_auditing -> { //结算审核
                val intent = Intent(mContext, MyWebViewActivity::class.java)
                val url = "${ApiContents.webBaseUrl}${globalData.CmpyCatg?.PreUrlForEmp}AuditList.aspx?AccessToken=${globalData.token?.access_token}"
                intent.putExtra("url",
                    url)
                intent.putExtra("title", "")
                intent.putExtra("hideNav", true)
                intent.putExtra("color", mColor)
                startActivity(intent)
            }
            R.id.ll_integrated_query -> { //综合查询
                val intent = Intent(mContext, MyWebViewActivity::class.java)
                val url = "${ApiContents.webBaseUrl}${globalData.CmpyCatg?.PreUrlForEmp}Search.aspx?AccessToken=${globalData.token?.access_token}"
                intent.putExtra("url",
                    url)
                intent.putExtra("title", "")
                intent.putExtra("hideNav", true)
                intent.putExtra("color", mColor)
                startActivity(intent)
            }
        }
    }

    override fun createPresenter(): ManagerPresenter {
        return ManagerPresenter(this)
    }

    override fun SuccessData(entity: WorkOrderReportEntity) {
        swiperefresh.isRefreshing = false
        loadLineChart(ArrayList())

        loadLineChart(entity.data.CountList)
    }

    override fun onRefresh() {
        mPresenter.getData()
    }
}